import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter_chat_ui/utils/audio_utils.dart';
import 'package:flutter_chat_ui/utils/utils.dart';
import 'package:flutter_chat_ui/views/chat_bottom_widgets/voice_controller.dart';
import 'package:get/get_state_manager/get_state_manager.dart';

///
/// 底部圆弧视图
///
class BottomOvalView extends StatelessWidget {
  const BottomOvalView({super.key});

  @override
  Widget build(BuildContext context) {
    return GetX<VoiceController>(
      builder: (controller) {
        bool isCanceling = controller.voiceStatus.value == VoiceStatus.cancelSend;

        return CustomPaint(
          painter: _VoiceBgOvalPainter(isFocus: !isCanceling),
          child: Container(
            width: double.infinity,
            height: Utils.voiceBgOvalHeight,
            alignment: Alignment.topCenter,
            child: Padding(
              padding: const EdgeInsets.only(top: 20),
              child: Text(
                isCanceling ? '取消 发送' : '松开 发送',
                style: const TextStyle(
                  fontSize: 15,
                  color: Colors.black,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ), // 提示文本【默认 松开发送 文本】
        );
      },
    );
  }
}

///
/// 绘制语音输入底部圆弧
///
class _VoiceBgOvalPainter extends CustomPainter {
  bool isFocus;

  _VoiceBgOvalPainter({
    this.isFocus = true,
  });

  @override
  void paint(Canvas canvas, Size size) {
    /// 绘制椭圆形
    final bgOvalRect = Rect.fromCenter(
      center: Offset(size.width * 0.5, size.height * 1.5),
      width: size.width * 1.8,
      height: size.height * 3,
    );

    final paint = Paint()
      ..color = const Color(0xff393939)
      ..style = PaintingStyle.fill;

    Path path = Path()..addOval(bgOvalRect);

    if (isFocus) {
      paint.color = const Color(0xffb0b0b0);
      canvas.drawPath(path, paint);

      final scale = (size.height * 3 - 8) / (size.height * 3);

      final bgShaderRect = Rect.fromCenter(
        center: bgOvalRect.center,
        width: bgOvalRect.width * scale,
        height: bgOvalRect.height * scale,
      );
      canvas.drawPath(
        Path()..addOval(bgShaderRect),
        Paint()
          ..shader = ui.Gradient.linear(
            Offset(size.width / 2, size.height),
            Offset(size.width / 2, 0),
            [
              const Color(0xffd5d5d5),
              const Color(0xff999999),
            ],
          ),
      );
    } else {
      canvas.drawPath(path, paint);
    }
  }

  @override
  bool shouldRepaint(covariant _VoiceBgOvalPainter oldDelegate) => true;

  @override
  bool shouldRebuildSemantics(covariant CustomPainter oldDelegate) => false;
}
